package just.stuff.morsels.util;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.IRequestTarget;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.IModel;

public class UpdateController implements Serializable {

	private List<Component> listeners = new LinkedList<Component>();
	
	public void registerListener( Component listener ) {
		listeners.add( listener );
	}
	
	public boolean unregisterListener( Component listener ) {
		return listeners.remove( listener );
	}
	
	public <K> UpdatingModel<K> wrap( IModel<K> model ) {
		return new UpdatingModel<K>( model );
	}
	
	private class UpdatingModel<K> implements IModel<K> {

		private IModel<K> model;
		
		private UpdatingModel(IModel<K> model) {
			this.model = model;
		}

		public void detach() {
			model.detach();
		}

		public K getObject() {
			return model.getObject();
		}

		public void setObject(K object) {
			model.setObject( object );
			notifyListeners();
		}

		private void notifyListeners() {
			RequestCycle cycle = RequestCycle.get();
			if( cycle != null ) {
				
				IRequestTarget target = cycle.getRequestTarget();
				if( target != null && target instanceof AjaxRequestTarget ) {
					AjaxRequestTarget ajaxTarget = (AjaxRequestTarget)target;
					for( Component listener : listeners ) {
						ajaxTarget.addComponent( listener );
					}
				}
			}
		}
	}
	
}
